<?php

namespace App\Http\Controllers\Admin;

use App\Http\Models\Links;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;


class LinksController extends CommonController
{
    // get admin/links
    public function index()
    {
        $links = Links::orderBy('link_order','asc')->get();
        return view('admin.links.index',compact('links'));
    }

    // DELETE admin/link/{id} 删除友情链接
    public function destroy($link_id)
    {
        $res = Links::where('link_id',$link_id)->delete();
        if($res){
            return array('status'=>0,'msg'=>'友情链接删除成功!');
        }else{
            return array('status'=>1,'msg'=>'友情链接删除失败!');
        }
    }

    // ajsx 修改排序
    public function changeOrder()
    {
        $input = Input::all();
        $field = Links::find($input['link_id']);
        $field->link_order = $input['link_order'];
        $res = $field->update();
        $data = array();
        if($res){
            $data['status'] = 0;
            $data['msg'] = '排序修改成功!';
        }else{
            $data['status'] = 1;
            $data['msg'] = '排序修改失败,请稍后再试!';

        }
        return $data;

    }

    // get admin/links/create
    public function create()
    {
        return view('admin.links.add');
    }

    // POST admin/links 入库
    public function store()
    {
        $input = Input::except('_token');
        // Validator 验证
        $rules = ['link_name'=>'required','link_url'=>'required'];
        $message = ['link_name.required'=>'友情链接名称不能为空!','link_url.required'=>'友情链接URL不能为空!'];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $res = Links::create($input);
            if($res){
                return redirect('admin/links');
            }else{
                return back()->with('errors','友情链接添加失败!');
            }
        }else{
            return back()->withErrors($validator);
        }
    }

    // 编辑 get admin/links/{id}/edit
    public function edit($link_id)
    {
        $field = Links::find($link_id);
        return view('admin.links.edit',compact('field'));
    }

    // PUT|PATCH admin/links/{id} 更新分类
    public function update($link_id)
    {
        $input = Input::except('_token','_method');
        // Validator 验证
        $rules = ['link_name'=>'required','link_url'=>'required'];
        $message = ['link_name.required'=>'友情链接名称不能为空!','link_url.required'=>'友情链接URL不能为空!'];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $res = Links::where('link_id',$link_id)->update($input);
            if($res){
                return redirect('admin/links');
            }else{
                return back()->with('errors','友情链接更新失败!');
            }
        }else{
            return back()->withErrors($validator);
        }

    }

}
